import {Coverage, TestParser} from '../../test-parser'
import {readFile,checkCoverageFileExist} from '../../utils'
import * as cheerio from 'cheerio'
import * as step from '@flow-step/step-toolkit'

export class PytestParser implements TestParser {
    async coverageFile(path: string): Promise<string> {
        if (!path.endsWith('.html')) {
            throw new Error(`Input variable 'reportPath' should reference a report with html extension`)
        }

        await checkCoverageFileExist(path)
        return path
    }

    htmlFile(path: string): string {
        return path
    }

  async parse(path: string): Promise<Coverage> {
      step.info(`Parsing Python-Pytest Html report: ${path}`)
      const htmlContent = await readFile(path)
      step.debug(`htmlContent: ${htmlContent}`)
      return this.count(htmlContent)
  }

  async count(htmlContent: string): Promise<Coverage>{
      const $ = cheerio.load(htmlContent)
      let res = {
          total : 0,
          passed : 0,
          failed : 0,
          skipped : 0,
          passedRate : 0
      } as Coverage

      res.passed = this.getBySelector($,'span.passed')
      res.failed = this.getBySelector($,'span.failed')
      res.skipped = this.getBySelector($,'span.skipped')
      const errorCounter = this.getBySelector($,'span.error')
      const xFailedCount = this.getBySelector($,'span.xfailed')
      const xPassedCount = this.getBySelector($,'span.xpassed')
      res.failed += errorCounter + xFailedCount + xPassedCount
      res.total = res.passed + res.failed + res.skipped

      if (res.total != 0){
          res.passedRate = Math.round(res.passed / res.total * 10000) / 100
      }
      return res
  }

    getBySelector($: cheerio.Root, span: string): number {
        const text = $(span).first().text().split(' ')[0];
        const val = parseInt(text, 10);

        if (isNaN(val)) {
            throw new Error('Error converting text to integer');
        }
        return val;
    }
}
